<template>
    <div>
        <van-tabbar>
            <div class="chatInput">
                <van-dropdown-menu direction="up">
                    <van-dropdown-item v-model="robotType" :options="robotTypeList" />
                </van-dropdown-menu>
                <van-field v-model="message" rows="2" type="textarea" maxlength="300" placeholder="请输入..." show-word-limit
                    clearable>
                    <template #button>
                        <van-button size="small" type="primary" @click="testMessage"
                            :disabled="shouldSend()">发送</van-button>
                    </template>
                </van-field>
            </div>
        </van-tabbar>
    </div>
</template>

<script>
const baseUrl = 'http://localhost:18080/mange/chat/talkVue?message='

// const baseUrl = 'http://8.216.66.88:9999/mange/chat/talkVue?message='
import { v4 as uuidv4 } from 'uuid'
export default {
    props: {
        robotId: {
            required: true,
            type: String
        }
    },
    name: 'SendMessage',
    data() {
        return {
            disable: false,
            message: '258 * 128=',
            eventSource: null,// 用于存储 EventSource 实例
            robotType: 'CHAT_4',
            isServerClosing: false,
            robotTypeList: [
                { text: 'gpt3.5', value: 'CHAT_3' },
                { text: 'gpt4.0', value: 'CHAT_4' }
            ],
            chatUuid: ''
        }
    },
    components: {},
    computed: {},
    methods: {
        // 过滤空数据
        shouldSend() {
          return (!this.disable & (this.message.trim() !== '')) === 0
        },
        testMessage() {
            this.chatUuid = uuidv4()
            // this.disable = true;
            this.$emit('sendChatMessage',
                {
                    uuid: this.chatUuid,
                    content: this.message,
                    type: 'user',
                    contentClass: 'chatContent user',
                    iamgeUrl: 'https://img01.yzcdn.cn/vant/cat.jpeg'
                }
            )
            console.log('robotId', this.robotId, uuidv4());
            
            this.sendMessage()
        }
        ,
        async sendMessage() {
            // 实现 用户说一句话 更新到 user.content页面去
            // 添加新消息到tableData
            // 判断是不是新建的
            console.log('sessionId:', this.robotId, this.robotId === null)
            // 添加新消息到tableData
            // 发送消息
            let url
            if (this.message.length > 200) {
                url = `${baseUrl}${this.message}&robotId=${encodeURIComponent(this.robotId)}&robotType=${encodeURIComponent(this.robotType)}`
            } else {
                url = `${baseUrl}${encodeURIComponent(this.message)}&robotId=${encodeURIComponent(this.robotId)}&robotType=${encodeURIComponent(this.robotType)}`
            }
            // 清空输入框
            this.message = ''
            this.openEventSource(url)
        },
        openEventSource(url) {
            // 如果之前有打开的 EventSource，先关闭它
            if (this.eventSource) {
                console.log('关闭之前的EventSource')
                this.eventSource.close()
            }
            console.log('创建新的EventSource', url)
            // 创建一个新的 EventSource 实例
            this.eventSource = new EventSource(url)
            try {
                this.eventSource.onmessage = (event) => {
                    const realData = event.data.replace(/"/g, '')

                    if (realData.includes('end')) {
                        this.isServerClosing = true
                        this.$emit('childEvent', {
                            message: realData,
                            uuid: this.chatUuid,
                            isDone: true
                        })
                    } else {
                        if (realData.trim()) {
                            this.$emit('childEvent', {
                                message: realData,
                                uuid: this.chatUuid,
                                isDone: false
                            })
                        }
                    }
                    console.log('realData', realData)
                }

                this.eventSource.onerror = (error) => {
                    if (this.eventSource.readyState === EventSource.CLOSED || this.isServerClosing) {
                        console.log('EventSource connection was closed.')
                    } else {
                        console.error('EventSource error:', error)
                        this.$message.error('服务异常')
                    }
                    this.eventSource.close()
                }
                console.log('EventSource opened', url, this.currentAiMessage)
            } catch (error) {
                console.error('EventSource error:', error)
                this.eventSource.close()
            }
        },
        beforeDestroy() {
            // 组件销毁前确保关闭 EventSource
            if (this.eventSource) {
                this.eventSource.close()
            }
        }
    }
}
</script>

<style scoped lang='scss'>
.chatInput {
    width: 100%;
}

.van-nav-bar {
    position: fixed;
    top: 0;
    width: 100%;
}

.van-nav-bar .van-icon {
    font-size: 25px;

    color: black;
}

::v-deep .van-dropdown-menu {
    display: flex;
    justify-content: flex-start;
    height: 30px;
}

.van-tabbar {
    height: 140px;
    max-height: 400px;

}

.van-button--normal {
    padding: 0 0px;
    font-size: 14px;
}

.van-dropdown-menu__bar {
    background-color: aqua;
    height: 30px;
}

::v-deep .van-dropdown-menu__item {
    height: 30px;
}
</style>
